package cn.exrick.sso.service.impl;

import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.IDUtil;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.dto.front.CartProduct;
import cn.exrick.manager.dto.front.OrderInfo;
import cn.exrick.manager.dto.front.PageOrder;
import cn.exrick.manager.mapper.TbItemMapper;
import cn.exrick.manager.mapper.TbMemberMapper;
import cn.exrick.manager.mapper.TbOrderItemMapper;
import cn.exrick.manager.mapper.TbOrderMapper;
import cn.exrick.manager.pojo.*;
import cn.exrick.sso.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {

    private final static Logger log= LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private TbMemberMapper tbMemberMapper;    //用户
    @Autowired
    private TbOrderMapper tbOrderMapper;    //订单
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;  //订单商品

    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Value("${CART_PRE}")
    private String CART_PRE;
    @Value("${IMAGE_ACCESS_URL}")
    private String imageUrl;

    @Override
    public PageOrder getOrderList(Long userId, int page, int size) {

        //分页
        if(page<=0) {
            page = 1;
        }
        PageHelper.startPage(page,size);

        PageOrder pageOrder=new PageOrder();

        TbOrderExample example=new TbOrderExample();
        TbOrderExample.Criteria criteria= example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andIsDelEqualTo((byte) 0);
        example.setOrderByClause("create_time DESC");
        List<TbOrder> listOrder =tbOrderMapper.selectByExample(example);
        for(TbOrder tbOrder:listOrder){
            judgeOrder(tbOrder);
            //商品
            List<TbOrderItem> listItem =tbOrderItemMapper.getOrderItemDatail(tbOrder.getOrderId());
            for(TbOrderItem orderItem : listItem){
                if(StringUtils.isNotBlank(orderItem.getPicPath())){
                    String[] images = orderItem.getPicPath().split(",");
                    orderItem.setPicPath(imageUrl + images[0]);
                }
            }
            tbOrder.setOrderItemList(listItem);
        }
        pageOrder.setTotal(getMemberOrderCount(userId));
        pageOrder.setData(listOrder);
        return pageOrder;
    }

    @Override
    public TbOrder getOrder(String orderId) {

        TbOrder tbOrder=tbOrderMapper.selectByPrimaryKey(orderId);
        if(tbOrder==null){
            throw new XmallException("通过id获取订单失败");
        }

        judgeOrder(tbOrder);

        //商品
        List<TbOrderItem> listItem =tbOrderItemMapper.getOrderItemDatail(tbOrder.getOrderId());
        for(TbOrderItem tbOrderItem:listItem){
            String[] images = tbOrderItem.getPicPath().split(",");
            tbOrderItem.setPicPath(imageUrl + images[0]);
        }
        tbOrder.setOrderItemList(listItem);
        return tbOrder;
    }

    @Override
    public int cancelOrder(String orderId) {

        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setStatus(CommonConstant.ORDER_STATUS_CANCEL);
        tbOrder.setFinishTime(new Date());
        if(tbOrderMapper.updateByPrimaryKeySelective(tbOrder)!=1){
            throw new XmallException("取消订单失败");
        }
        return 1;
    }

    @Override
    public Result<Object> createOrder(OrderInfo orderInfo) {
        //判断库存是否足够
        List<CartProduct> list=orderInfo.getGoodsList();
        List<Long> itemIdList = new ArrayList<>(list.size());
        Map<Long,CartProduct> map = new HashMap<>();
        for(CartProduct cartProduct : list){
            map.put(cartProduct.getProductId(),cartProduct);
            itemIdList.add(cartProduct.getProductId());
        }
        TbItemExample example = new TbItemExample();
        TbItemExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(itemIdList);
        List<TbItem> tbItems = tbItemMapper.selectByExample(example);
        String errorMsg = "";
        for(TbItem tbItem : tbItems){
            CartProduct cartProduct = map.get(tbItem.getId());
            if(tbItem.getNum() < cartProduct.getProductNum()){
                errorMsg += "商品" + tbItem.getTitle() + "库存剩余" + tbItem.getNum() + "件，";
            }
        }

        if(StringUtils.isNotBlank(errorMsg)){
            errorMsg += "请调整购买数量！";
            return new ResultUtil<>().setErrorMsg(errorMsg);
        }

        TbMember member=tbMemberMapper.selectByPrimaryKey(Long.valueOf(orderInfo.getUserId()));
        if(member==null){
            throw new XmallException("获取下单用户失败");
        }

        TbOrder order=new TbOrder();
        //生成订单ID
        String orderId = IDUtil.getRandomId();
        order.setOrderId(orderId);
        order.setOrderNo(IDUtil.getOrderNo());
        order.setCode(IDUtil.getOrderCode());
        order.setIsDel(false);
        order.setDeliveryType(CommonConstant.DELIVER_TYPE_SELF);
        order.setUserId(Long.valueOf(orderInfo.getUserId()));
        order.setPayType(orderInfo.getPayType());
        //总金额
        order.setTotalAmount(orderInfo.getOrderTotal());
        //应付金额
        order.setPayment(orderInfo.getPayment());
        if(orderInfo.getPayType() == CommonConstant.PAY_TYPE_ALIPAY){
            //支付宝支付金额
            order.setPayMoney(orderInfo.getPayment());
            //部门余额支付金额
            order.setPayBalance(new BigDecimal(0));
        }else if (orderInfo.getPayType() == CommonConstant.PAY_TYPE_BALANCE){
            order.setPayMoney(new BigDecimal(0));
            order.setPayBalance(orderInfo.getPayment());
        }

        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        if(CommonConstant.PAY_TYPE_BALANCE == order.getPayType()){
            order.setStatus(CommonConstant.ORDER_STATUS_ORG_CHARGE_APPROVAL);
        }else{
            order.setStatus(CommonConstant.ORDER_STATUS_PAYING);
        }

        if(tbOrderMapper.insert(order)!=1){
            throw new XmallException("生成订单失败");
        }


        for(CartProduct cartProduct:list){
            TbOrderItem orderItem=new TbOrderItem();
            //生成订单商品ID
            orderItem.setId(IDUtil.getRandomId());
            orderItem.setItemId(String.valueOf(cartProduct.getProductId()));
            orderItem.setOrderId(orderId);
            orderItem.setNum(Math.toIntExact(cartProduct.getProductNum()));
            orderItem.setPrice(cartProduct.getSalePrice());

            if(tbOrderItemMapper.insert(orderItem)!=1){
                throw new XmallException("生成订单商品失败");
            }

            //删除购物车中含该订单的商品
            try{
                List<String> jsonList = jedisClient.hvals(CART_PRE + ":" + orderInfo.getUserId());
                for (String json : jsonList) {
                    CartProduct cart = new Gson().fromJson(json,CartProduct.class);
                    if(cart.getProductId().equals(cartProduct.getProductId())){
                        jedisClient.hdel(CART_PRE + ":" + orderInfo.getUserId(),cart.getProductId()+"");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return new ResultUtil<>().setData(orderId);
    }

    @Override
    public void delOrder(String orderId) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setUpdateTime(new Date());
        tbOrder.setIsDel(true);
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
    }

    @Override
    public void payOrder(String orderId,String tradeNo) {

        //设置订单为已付款
        TbOrder tbOrder=tbOrderMapper.selectByPrimaryKey(orderId);
        tbOrder.setStatus(CommonConstant.ORDER_STATUS_DELIVER);
        tbOrder.setTradeNo(tradeNo);
        tbOrder.setUpdateTime(new Date());
        tbOrder.setPayTime(new Date());
        if(tbOrderMapper.updateByPrimaryKey(tbOrder)!=1){
            throw new XmallException("更新订单失败");
        }

        //更新商品库存
        List<TbOrderItem> orderItemList =tbOrderItemMapper.getOrderItemDatail(tbOrder.getOrderId());
        for(TbOrderItem tbOrderItem : orderItemList){
            tbItemMapper.reduceNum(Long.valueOf(tbOrderItem.getItemId()),tbOrderItem.getNum());
        }
    }

    /**
     * 判断订单是否超时未支付
     */
    public String judgeOrder(TbOrder tbOrder){

        String result=null;
        if(tbOrder.getStatus()==CommonConstant.ORDER_STATUS_PAYING){
            //判断是否已超1小时
            long diff=System.currentTimeMillis()-tbOrder.getCreateTime().getTime();
            long hours = diff / (1000 * 60 * 60);
            if(hours>=1){
                //自动取消
                tbOrder.setStatus(CommonConstant.ORDER_STATUS_CANCEL);
                tbOrder.setFinishTime(new Date());
                tbOrder.setRemark("超时未支付");
                if(tbOrderMapper.updateByPrimaryKey(tbOrder)!=1){
                    throw new XmallException("订单取消失败");
                }
            }else {
                //返回到期时间
                long time=tbOrder.getCreateTime().getTime()+1000 * 60 * 60;
                result= String.valueOf(time);
            }
        }
        return result;
    }

    public int getMemberOrderCount(Long userId){

        TbOrderExample example=new TbOrderExample();
        TbOrderExample.Criteria criteria= example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andIsDelEqualTo((byte) 0);
        List<TbOrder> listOrder =tbOrderMapper.selectByExample(example);
        if(listOrder!=null){
            return listOrder.size();
        }
        return 0;
    }
}
